package study06_webchat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;

/**
 * @author kdyzm
 */
@Slf4j
public class WebChatHandler extends ChannelInboundHandlerAdapter {

    //创建一个ChannelGroup
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        group.forEach(item -> {
            if (channel != item) {
                item.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
                return;
            }
            item.writeAndFlush("me:" + msg + "\n");
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        log.info("{}上线", socketAddress);
        group.writeAndFlush(socketAddress + " 上线");
        group.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        log.info("{}下线", socketAddress);
        group.writeAndFlush(socketAddress + "下线，剩余在线人数：" + group.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("", cause);
        ctx.close();
    }
}
